using Microsoft.AspNetCore.Mvc;
using FirstTea.Domain.Entities;
using FirstTea.Infrastructure;
using Microsoft.EntityFrameworkCore;

namespace FirstTea.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ProductController : ControllerBase
    {
        private readonly FirstTeaDbContext _db;
        public ProductController(FirstTeaDbContext db)
        {
            _db = db;
        }

        // 商品详情接口
        [HttpGet("{id}")]
        public async Task<ActionResult<Tea>> GetTeaDetail(Guid id)
        {
            var tea = await _db.Teas.Include(t => t.TeaType)
                .Include(t => t.Reviews)
                .FirstOrDefaultAsync(t => t.Id == id);
            if (tea == null) return NotFound();
            return tea;
        }

        // 商品评论列表
        [HttpGet("{id}/reviews")]
        public async Task<ActionResult<IEnumerable<Review>>> GetTeaReviews(Guid id)
        {
            var reviews = await _db.Reviews.Where(r => r.TeaId == id)
                .Include(r => r.User)
                .OrderByDescending(r => r.CreatedAt)
                .ToListAsync();
            return reviews;
        }

        // 新增评论
        [HttpPost("{id}/reviews")]
        public async Task<ActionResult<Review>> AddReview(Guid id, [FromBody] Review review)
        {
            review.TeaId = id;
            // 时间字段由 Review 构造函数自动赋值
            _db.Reviews.Add(review);
            await _db.SaveChangesAsync();
            return CreatedAtAction(nameof(GetTeaReviews), new { id }, review);
        }
    }
}
